import React, { useEffect, useState, useImperativeHandle, forwardRef } from 'react';
import { withRouter } from 'react-router-dom'
import { Card, Form, Input, Button, Radio, message, Checkbox, Select, InputNumber } from 'antd';
import BreadcrumbBox from '@/components/Base/BreadcrumbBox';
import { checkRules, useDebounceFn } from '@/utils'
import { add, listRole, getInfoById, update } from '@/api/role'
import { deepclone, useSyncCallback } from '@/utils'
import './index.scss';

// eslint-disable-next-line no-unused-vars
const ChildAccount = forwardRef((props, ref) => {
  const breadcrumbList = ['角色管理', '子账号管理']
  const [addForm] = Form.useForm();
  const [listOptions, setListOptions] = useState([]);
  const [info, setInfo] = useState(null);
  const [id, setId] = useState('');
  const [loading, setLoading] = useState(false);
  
  
  const [data] = useState({  
    "userName": "",
    "password": "",
    "transPwd": "",
    "nickName": "",
    "roleId": "",
  })
  // 提交弹框表单做防抖处理
  const submitOk = useDebounceFn((values) => {
    onFinish(values)
  }, 1500, true);
  const onFinish = async (values) => {
    try {
      let params = {
        ...values,
      }
      let res = id ? await update(params) : await add(params)
      if (res.code === 0) {
        message.destroy()
        if(id){
          message.success('修改成功')
          getInfo()
        }else{
          message.success('添加成功')
          addForm.resetFields()
        }
      }
    } catch (error) {
      console.log(error)
    }
  };
   
   
   const getInfo = async () => {
     try {
       setInfo(null)
       setLoading(true)
       let res = await getInfoById({
         managerUserId: id,
       })
       if(res.code === 0) {
         res.data.roleId = res.data.roleId
         setInfo(res.data)
         addForm.setFieldsValue({
          ...res.data
         })
       }
       setLoading(false)
     } catch(error) {
       console.log(error)
     }
   }
   // 获取账号权限
  const listRoleHanlder = async () => {
    try {
      let res = await listRole()
      if(res.code === 0) {
        let arr = []
        res.data.forEach(item=>{
          arr.push({
            value: item.id,
            label: item.name,
          })
        })
        setListOptions(arr)
      }
    } catch(error) {
      console.log(error)
    }
  }
  // 等state改变后再执行
  const searchData = useSyncCallback(() => {
    getInfo()
  })
   // 初始化
   useEffect(() => {
     if(props.params&&props.params.id){
       setId(props.params.id)
       searchData()
     }
    listRoleHanlder()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  return (
    <div className='pass-component'>
      <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
      <div className='pass-main'>
        <Card loading={loading}>
          <div className='pass-form'>
            <Form
              name="basic"
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 16 }}
              form={addForm}
              initialValues={data}
              autoComplete="new-password"
              onFinish={submitOk}>
              <Form.Item
                label="总后台账号"
                name="userName"
                rules={[
                  { required: true, message: '请输入后台管理账号!' },
                ]}
              >
                {
                  id
                  ?
                  info&&info.userName
                  :
                  <Input />
                }
              </Form.Item>
              <Form.Item
                label="登录密码"
                name="password"
                rules={[
                  { required: true, message: '请输入登录密码!' },
                  // checkRules('password')
                ]}
              >
                <Input.Password />
              </Form.Item>
              {
                id
                ?
                ''
                :
                <Form.Item
                  label="交易密码"
                  name="transPwd"
                  rules={[
                    { required: true, message: '请输入交易密码!' },
                    // checkRules('password')
                  ]}
                >
                  <Input.Password />
                </Form.Item>
              }
              <Form.Item
                label="账户名称"
                name="nickName"
                rules={[
                  { required: true, message: '请输入账户名称!' },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="赋予角色"
                name="roleId"
                rules={[
                  { required: true, message: '请选择赋予角色' },
                ]}
              >
                <Select options={listOptions} />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
                <Button style={{marginLeft: '10px'}} onClick={()=>{
                  props.setPageType("list")
                  props.setParams({
                    id: ''
                  })}
                }>
                  返回
                </Button>
              </Form.Item>
            </Form>
          </div>
        </Card>
      </div>
    </div>
  )
})
export default ChildAccount